import { _decorator, Component, Node, tween, Vec3, RigidBody, PhysicsSystem, geometry, Prefab, instantiate, director, CapsuleCollider, ITriggerEvent, Camera } from 'cc';
import { eventCenter } from '../Utils/JJWXR_EventCenter';
import { JJWXR_Events } from '../Utils/JJWXR_Events';
import { JJWXR_Player } from './JJWXR_Player';
const { ccclass, property } = _decorator;

@ccclass('JJWXR_Bullet')
export class JJWXR_Bullet extends Component {

    @property(Prefab)
    private bulletEffect: Prefab = null;
    @property(Camera)
    private camera: Camera = null;

    public timeScale: number = 0.2; // 子弹时间的时间缩放（0.2 表示 20% 的速度）
    private speed: number = 2; // 移动速度
    private bulletTimeSpeed: number = 40; // 子弹时间的移动速度

    private lifeTime: number = 0.3; // 子弹的存活时间（秒）
    private bulletTimeLifeTime: number = 5; // 子弹时间的存活时间（秒）
    private rigidBody: RigidBody = null; // 子弹的刚体组件
    private direction: Vec3 = Vec3.FORWARD; // 移动方向

    public isBulletTime: boolean = false; // 是否处于子弹时间状态

    private hitPos: any = null; // 子弹击中的位置

    start() {
        // 获取刚体组件
        this.rigidBody = this.node.getComponent(RigidBody);
        this.rigidBody.useCCD = true;

        // 初始化子弹
        this.direction = this.node.forward;

        this.isBulletTime = JSON.parse(localStorage.getItem("isBulletTime") || "false");

        this.camera.node.active = false;

        // 射线检测
        this.fireRaycast();
        if (!this.isBulletTime) {
            // 自动销毁子弹
            this.scheduleOnce(() => {
                this.destroyBullet();
            }, this.lifeTime);
        } else {
            // 自动销毁子弹
            this.scheduleOnce(() => {
                this.destroyBullet();
            }, this.bulletTimeLifeTime);// 子弹时间射线检测
        }

    }

    // 子弹时间碰撞检测  
    onTriggerEnter(event: ITriggerEvent) {
        event.otherCollider.node.getComponent(JJWXR_Player); // 获取碰撞的节点
        this.spawnHieEffect(this.hitPos);
        this.destroyBullet(); // 销毁子弹
        eventCenter.emit(JJWXR_Events.ENEMY_DESTROY, this.hitPos.collider.node.parent);
    }

    // // 移动子弹
    // move(deltaTime: number) {
    //     // // 根据方向和速度移动子弹
    //     // const newPosition = this.node.position.clone();
    //     // Vec3.scaleAndAdd(newPosition, newPosition, this.direction, this.speed * deltaTime);
    //     // // newPosition.z += this.direction.z * this.speed * deltaTime;
    //     // // newPosition.y += this.direction.y * this.speed * deltaTime;
    //     // // newPosition.x += this.direction.x * this.speed * deltaTime;
    //     // this.node.setPosition(newPosition);

    //     // 使用刚体组件移动子弹
    //     this.rigidBody.setLinearVelocity(this.direction.multiplyScalar(this.speed)); // 使用刚体组件移动子弹

    // }


    moveBulletTime() {
        // console.log("子弹时间移动" + this.node.position);
        eventCenter.emit(JJWXR_Events.HIDE_RETICLE_UI);
        // // 使用刚体组件移动子弹
        this.rigidBody.setLinearVelocity(this.direction.multiplyScalar(this.bulletTimeSpeed)); // 使用刚体组件移动子弹
    }

    // 摄像机跟随方法
    followTarget() {
        this.camera.node.active = true;
        // 检查摄像机是否设置
        if (!this.camera) {
            console.error("摄像机未设置");
            return;
        }
        // 获取摄像机节点
        const cameraNode = this.camera.node;
        // 设置摄像机的位置和旋转
        // cameraNode.position = this.node.position.add(new Vec3(-30, 0, 0)); // 调整摄像机的位置
        cameraNode.lookAt(this.node.position); // 让摄像机看向目标
    }

    // 射线检测
    fireRaycast() {
        // 创建射线
        const ray = new geometry.Ray(
            this.node.position.x, this.node.position.y, this.node.position.z, // 起点
            this.direction.x, this.direction.y, this.direction.z // 方向
        );

        // 射线检测
        if (PhysicsSystem.instance.raycast(ray)) {
            // 获取碰撞结果
            const results = PhysicsSystem.instance.raycastResults;
            // 处理碰撞结果
            for (let i = 0; i < results.length; i++) {
                const hit = results[i];
                const hitNode = hit.collider;
                console.log("子弹击中了物体, 分组为: " + hitNode.getGroup());
                if ((hitNode.getGroup() === 4 || hitNode.getGroup() === 8) && this.isBulletTime) {
                    this.hitPos = results[i];
                    // 获取碰撞组件
                    let collider = this.getComponent(CapsuleCollider);
                    // 监听碰撞事件
                    if (collider) {
                        collider.on('onTriggerEnter', this.onTriggerEnter, this);
                    }
                    // 开启摄像机跟随
                    console.log("开启摄像机跟随");
                    this.followTarget();
                    this.moveBulletTime();
                    break;
                }
                else {
                    this.checkHit(hit, hitNode.getGroup())
                }

            }
        }
    }

    // 检查命中的物体
    private checkHit(hit: any, index: number) {
        if (index === 4 || index === 8) {
            // 播放精确命中特效
            const HitPosition = hit.hitPoint;
            this.spawnHieEffect(HitPosition);
        }

        // 销毁子弹
        this.destroyBullet();

        // 播放精确命中音效

        if (index === 4) {

            let headShot = JSON.parse(localStorage.getItem("headShot")) || 0;
            console.log(headShot);
            let shothead = headShot + 1;
            localStorage.setItem("headShot", JSON.stringify(shothead));

            let hitShot = JSON.parse(localStorage.getItem("hitShot")) || 0;
            console.log(hitShot);
            let shotHit = hitShot + 1;
            localStorage.setItem("hitShot", JSON.stringify(shotHit));

            
            // 播放精确命中动画
            eventCenter.emit(JJWXR_Events.SHOWPRECISEHIT);
            console.log("精确命中");
            // 敌人死亡
            eventCenter.emit(JJWXR_Events.ENEMY_DESTROY, hit.collider.node.parent);
        }
        else if (index === 8) {
            // 播放命中动画
            // 敌人死亡
            // enemy.destroyEnemy();

            let hitShot = JSON.parse(localStorage.getItem("hitShot")) || 0;
            console.log(hitShot);
            let shot = hitShot + 1;
            localStorage.setItem("hitShot", JSON.stringify(shot));

            eventCenter.emit(JJWXR_Events.ENEMY_DESTROY, hit.collider.node.parent);
        }
    }

    // 生成命中特效
    private spawnHieEffect(position: Vec3) {
        // 实例化特效
        const effect = instantiate(this.bulletEffect);
        // 添加到场景中
        director.getScene().addChild(effect);
        // 设置特效位置
        effect.setPosition(position);

        // 延迟销毁
        this.scheduleOnce(() => {
            effect.destroy();
        }, 1.2);
    }

    // 销毁子弹
    destroyBullet() {
        this.node.destroy();
    }
}